package com.xiaoluo.web;


import com.xiaoluo.cd.entity.base.Jobs;
import com.xiaoluo.cd.entity.base.Projects;
import com.xiaoluo.cd.entity.base.Version;
import com.xiaoluo.common.enums.JobModeEnum;
import com.xiaoluo.common.enums.JobStatusEnum;
import com.xiaoluo.common.enums.JobTypeEnum;
import com.xiaoluo.common.enums.ServerTypeEnum;
import com.xiaoluo.common.queue.BuildLogMap;
import com.xiaoluo.common.queue.JobQueue;
import com.xiaoluo.service.JobService;
import com.xiaoluo.service.KubernetesService;
import com.xiaoluo.service.ProjectService;
import com.xiaoluo.service.VersionService;
import com.xiaoluo.web.form.JobForm;
import com.xiaoluo.web.form.ProjectForm;
import com.xiaoluo.web.form.ResultForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * Project : SpiderManager
 * Package : com.xiaoluo.web
 * Created by Willian.
 * Date  : 2015/10/21 20:29.
 */
@Controller
@RequestMapping("/job")
public class JobController extends BaseController{
    private final static Logger logger = LoggerFactory.getLogger(JobController.class);

    private final static Integer pageSize = 14;
    @Autowired
    private JobService jobService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private VersionService versionService;
    @Autowired
    private KubernetesService kubernetesService;

    @RequestMapping(method = RequestMethod.GET)
    public  String index(ModelMap model,String keyword){

        return "index";
    }

    @RequestMapping(value = "/build")
    public  String build(ModelMap model,Long id){
        /**
         * 1、新建job;
         * 2、提交任务;
         * 3、返回任务列表
         */
        logger.info("request parameter id ={}",id);

        if(id != null){
            Version version =  versionService.getVersion(id);
            Projects projects = projectService.get(version.getProjId());
            //提交任务
            jobService.submit(projects,version, JobModeEnum.NORMAL);
            //获取任务列表
            List<JobForm> jobsList = jobService.list(id, (int) JobTypeEnum.BUILD.getValue(), null, null,null);
            model.addAttribute("project",projects);
            model.addAttribute("jobs",jobsList);
            model.addAttribute("version",version);
        }

        return "redirect:/job/jobs?id="+id;
    }

    @RequestMapping(value = "/buildLcol")
    public  String buildLcol(ModelMap model,Long id){
        /**
         * 1、新建job;
         * 2、提交任务;
         * 3、返回任务列表
         */
        logger.info("request parameter id ={}",id);

        if(id != null){
            Version version =  versionService.getVersion(id);
            Projects projects = projectService.get(version.getProjId());
            //提交任务
            jobService.submit(projects,version,JobModeEnum.NORMAL);
            //获取任务列表
            List<JobForm> jobsList = jobService.list(id, (int) JobTypeEnum.BUILD.getValue(), null, null,null);
            model.addAttribute("project",projects);
            model.addAttribute("jobs",jobsList);
            model.addAttribute("version",version);
        }

        return "redirect:/job/jobs?id="+id;
    }


    @RequestMapping(value = "/jobs")
    public  String queryJobs(ModelMap model,@RequestParam Long id,String commitName,
                             @RequestParam(value = "pageIndex",defaultValue = "0") Integer pageIndex,
                             @RequestParam(value = "pageSize",defaultValue = "30") Integer pageSize,
                             HttpServletRequest request){
        /**
         * 1、运行build脚本;
         * 2、输出运行结果;
         */
        logger.info("request parameter id ={}",id);

        if(id != null){
            Version version = versionService.getVersion(id);
            ProjectForm projects = projectService.findById(version.getProjId());
            List<JobForm> jobsList = jobService.list(id, 0, pageIndex, pageSize,commitName);

            model.addAttribute("project",projects);
            model.addAttribute("jobs",jobsList);
            model.addAttribute("version",version);
        }

        return "project/jobs";
    }
    @RequestMapping(value = "/query")
    public  String queryJobsByUuid(ModelMap model,@RequestParam String uuid,String commitName,
                             @RequestParam(value = "pageIndex",defaultValue = "0") Integer pageIndex,
                             @RequestParam(value = "pageSize",defaultValue = "30") Integer pageSize,
                             HttpServletRequest request){
        /**
         * 1、运行build脚本;
         * 2、输出运行结果;
         */
        logger.info("request parameter id ={}",uuid);

        if(uuid != null){
            Jobs jobs = jobService.get(uuid);
            if(jobs != null){
                Version version = versionService.getVersion(jobs.getVersionId());
                ProjectForm projects = projectService.findById(version.getProjId());
                List<JobForm> jobsList = jobService.list(jobs.getVersionId(), 0, pageIndex, pageSize,commitName);

                model.addAttribute("project",projects);
                model.addAttribute("jobs",jobsList);
                model.addAttribute("version",version);
            }
        }
        return "project/jobs";
    }

    @RequestMapping(value = "/detail")
    public  String detail(ModelMap model,@RequestParam Long id,HttpServletRequest request){
        Jobs job = jobService.get(id);
        if(job!=null){
            Projects project = projectService.get(job.getProjId());
            Jobs testJob = jobService.get(id, JobTypeEnum.TEST.getValue());
            Jobs deployJob = jobService.get(id, JobTypeEnum.DEPLOY.getValue());

            model.addAttribute("project",project);
            model.addAttribute("buildJob",job);
            model.addAttribute("testJob",testJob);
            model.addAttribute("deployJob",deployJob);
        }

        return "job/detail";
    }

    @RequestMapping(value = "/queryChildren")
    @ResponseBody
    public ResultForm queryChildren(ModelMap model,@RequestParam Long id){
        ResultForm result = new ResultForm(0,"");
        result.setData(jobService.getChildren(id));
        return result;
    }

    @RequestMapping(value = "/doRun")
    @ResponseBody
    public ResultForm doRun(ModelMap model,
                             @RequestParam Long id,
                             @RequestParam String type,
                             @RequestParam(value = "env", required = false,defaultValue = "NORMAL") String env,
                             @RequestParam(value = "m", required = false,defaultValue = "0")  String m,
                             HttpServletRequest request){

        ResultForm result = new ResultForm(0,"");
        /**
         * 1、运行build脚本;
         * 2、输出运行结果;
         */
        logger.info("request parameter id ={}",id);

        if(id != null){
            boolean isExist = jobService.isExist(id, (int) JobTypeEnum.valueOf(type).getValue());
            if(!isExist){
                Jobs jobs = jobService.get(id);

                Projects projects = projectService.get(jobs.getProjId());
                jobService.submit(projects,id, JobTypeEnum.valueOf(type),JobModeEnum.valueOf(env));
            }else {
                //重新部署
                Jobs jobs = jobService.get(id, JobTypeEnum.valueOf(type).getValue());

                if("0".equals(m)){
                    jobs.setJobMode(JobModeEnum.valueOf(env).getValue());
                    jobService.submit(jobs);
                }
                result.setData(jobs);
            }
        }

        return result;
    }
    @RequestMapping(value = "/getLog")
    @ResponseBody
    public ResultForm getLog(ModelMap model,
                            @RequestParam Long id,
                            @RequestParam String type,
                            HttpServletRequest request){

        ResultForm result = new ResultForm(0,"");
        Jobs jobs;
        /**
         * 1、运行build脚本;
         * 2、输出运行结果;
         */
        logger.info("request parameter id ={}",id);

        if(id != null){

            JobTypeEnum typeEnum = JobTypeEnum.valueOf(type);

            if(typeEnum == JobTypeEnum.BUILD){
                jobs = jobService.get(id);
            }else{
                jobs = jobService.get(id,typeEnum.getValue());
            }

            if(jobs != null){
                if(jobs.getJobStatus()== JobStatusEnum.RUN.getValue()){
                    List<String> list = BuildLogMap.get(jobs.getJobName() + "_" + jobs.getJobType());
                    if(list != null){
                        StringBuffer buf = new StringBuffer();
                        for(String line:list){
                            buf.append(line).append("\r");
                        }
                        jobs.setJobDesc(buf.toString());
                    }else {
                        jobs.setJobDesc("Running...");
                    }
                }
                result.setData(jobs);
            }

        }

        return result;
    }

}
